loadScript("../js/bootstrap5.bundle.min.js")

const menuContent = [{
    name: "rate",
    icon: "icon-doc-add",
    sub: [{name: "org", caption: "Org. Mgt.", link: "./organization/organization.html"},
        {name: "company", caption: "Company Mgt.", link: "./company/company.html"},
        {name: "currency", caption: "Currency Mgt.", link: "./currency/currency.html"},
        {name: "charge_code", caption: "Charge Code Mgt.", link: "./charge_code/chargecode.html"},
        {name: "client_rate", caption: "Client Rate", link: "./clientrate/clientrate.html"},
        {name: "client_rate_charge", caption: "Client Rate Charge", link: "./clientrate/clientratecharge.html"}]
}, {
    name: "warehouse", icon: "icon-warehouse",
    sub: [{
        name: "order", caption: "Warehouse Order", link: "./warehouseorder/warehouseorder.html", target: "desktop"
    }, {
        name: "receive",
        caption: "Warehouse Receive",
        link: "./warehousereceive/warehousereceive.html",
        target: "desktop"
    },
        {name: "mapper", caption: "Code Mapper", link: "./codemapper/codemapper.html", target: "desktop"}
    ]
}, {
    name: "GPS", icon: "icon-money",
    sub: [{name: "billInfo", caption: "Bill Info", link: "./bill/bill.html", target: "desktop"},
        {name: "exchangeRate", caption: "Exchange Rate", link: "./currency/exchange.html", target: "desktop"},
        {name: "carrierTemplate", caption: "Carrier Template", link: "./client/template.html", target: "desktop"},
        {name: "ar", caption: "AR", link: "./ar/ar.html", target: "desktop"},
        {name: "ap", caption: "AP", link: "./ap/ap.html", target: "desktop"},
        {name: "ar_statement", caption: "AR Statement", link: "./ar/ar_report.html", target: "desktop"},
        {name: "ap_statement", caption: "AP Statement", link: "./ap/ap_report.html", target: "desktop"},
        {name: "task", caption: "Task List", link: "./task/task.html", target: "desktop"},
    ]
}, {
    name: "crm", icon: "icon-flow-tree",
    sub: [{
        name: "customer",
        caption: "Customer",
        link: "./warehouseorder/warehouseorder.html",
        target: "desktop"
    }, {name: "contact", caption: "Contact", link: "./codemapper/codemapper.html", target: "desktop"},
        {name: "event", caption: "Event", link: "", target: "desktop"}]
}, {
    name: "setting", icon: "icon-cog", sub: [
        {caption: "User", link: "./user/user.html", target: "desktop"},
        {caption: "Account", link: "./account/account.html", target: "desktop"},
        {caption: "Role", link: "./role/role.html", target: "desktop"},
        {caption: "Operation", link: "./operation/operation.html", target: "desktop"},
        {caption: "File", link: "./file/file.html", target: "desktop"},
        {caption: "Template", link: "./template/template.html", target: "desktop"}
    ]
}, {
    name: "tool", icon: "icon-cog", sub: [
        {caption: "Column Tool", modal: "modal#columnTool"}
    ]
}];

let renderRightMenu = (data) => {
    let renderMenuItem = (dataItem) => {
        let target = `target="${dataItem.target || "desktop"}"`;
        if(dataItem.modal){
            let param = dataItem.modal.split("#");
            target = ` data-bs-toggle="${param[0]}" data-bs-target="#${param[1]}"`;
        }else if(dataItem.action){
            target = `onclick="${dataItem.action}"`;
        }else if(dataItem.link){
            target += `href="${dataItem.link??'#'}"`;
        }
        let menuItem = `<li class="nav-item">+
        <a class="nav-link active" aria-current="page" ${target}>${dataItem.caption}</a>
    </li>`;
        return _e(menuItem);
    };
    let menuWrapper = document.getElementById("menu").querySelector("ul");
    menuWrapper.innerHTML = "";
    Array.isArray(data) && data.forEach(dataItem => {
        const item = renderMenuItem(dataItem);
        item.addEventListener("click", () => {
            item.parentNode.childNodes.forEach(i => i.classList?.remove("active"));
            item.classList?.add("active");
        });
        menuWrapper.appendChild(item)
    });
}

let renderIconMenu = (opt) => {
    let iconWrapper = document.getElementById("iconMenu").querySelector("nav");
    let icons = opt.map((icon, index) => {
        let tmp = `<a class="nav-link py-3 nav-icon-link" data-sequence="${index}">
            <i class="bi fs-4 ${icon.icon}"></i>
        </a>`;
        return _e(tmp);
    });
    const clickEvent = (e) => {
        icons.filter(icon => e.target !== icon && !icon.contains(e.target)).forEach(i => i.classList?.remove("active"));
        let clickIcon = icons.find(icon => e.target === icon || icon.contains(e.target));
        clickIcon.classList?.add("active");
        renderRightMenu(opt[clickIcon.dataset.sequence].sub);
    }
    icons.forEach(i => i.addEventListener("click", clickEvent));
    icons.forEach(i => iconWrapper.appendChild(i));
    icons[0].click();
}


const iframe = document.getElementById("desktop");
document.getElementById("desktopSize").addEventListener("change", () => {
    document.body.style.fontSize = document.getElementById("desktopSize").value;
    const doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.body.style.fontSize = document.getElementById("desktopSize").value;
});

iframe.onload = () => {
    const doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.body.style.fontSize = document.getElementById("desktopSize").value;
};



renderIconMenu(menuContent);

// Resizer logic
const resizer = document.getElementById('resizer');
const menuContainer = document.getElementById("menu");
const menu = menuContainer;
const minWidth = 100; // minimum width of menu
const maxWidth = 600; // maximum width of menu

let isResizing = false;

resizer.addEventListener('mousedown', function (e) {
    isResizing = true;
    document.body.classList.add('resizing');
    e.preventDefault(); // prevent text selection
});

document.addEventListener('mousemove', function (e) {
    if (!isResizing) return;
    let newWidth = e.clientX - 60;
    if (newWidth < minWidth) newWidth = minWidth;
    if (newWidth > maxWidth) newWidth = maxWidth;
    menu.style.width = newWidth + 'px';
});

document.addEventListener('mouseup', function () {
        if (isResizing) {
            isResizing = false;
            document.body.classList.remove('resizing');
        }
    }
);

const params = new URLSearchParams(window.location.search);
const url = params.get("url");
if (url && url.indexOf(".") !== -1) {
    let arr = url.split(".");
    let sub = menuContent.find(i => i.name === arr[0]).sub;
    if (sub) {
        let link = sub.find(i => i.name === arr[1]);
        if (link)
            window.open(link.link, link.target)
    }
}

window.onload = function () {
    ct();
    ajax("/account/info", {}, data => {
        let userName = data.data.user.userName;
        document.querySelector("#userCap").innerHTML = userName.trim()
            .split(/\s+/)
            .map(word => word.charAt(0).toUpperCase())
            .join('');
    })
}

function logout() {
    localStorage.removeItem("Authorization");
}

function ct(){
    let element = modal("columnTool");
    let container = element.querySelector(".modal-body");
    let source = _e("<input type=\"text\" class=\"form-control\" placeholder=\"数据\">");
    let table = _e("<table id='columnToolTable'  class=\"table table-bordered align-middle\"></table>");
    let target = _e("<input type=\"text\" class=\"form-control\" placeholder=\"结果\">");
    source.addEventListener("keydown", function(event) {
        if (event.key === "Enter") {
            event.preventDefault();
            table.innerHTML="";
            let value = source.value.split("\t");
            for (const val of value) {
                let line = `<tr>
                <th>${val}</th>
                <td><input type="input" class="form-control"/></td>
            </tr>`;
                table.append(_e(line,"table"));
            }
        }
    });
    container.append(source, table, target);
     element.querySelector("button[name='commit']").addEventListener("click",function(event){
         target.value = "";
         let items = [];
         table.querySelectorAll("tr").forEach(tr=>{
             if(tr.querySelector("input").value){
             items[items.length] = "\""+tr.querySelector("th").innerText+"\",\""+tr.querySelector("input").value+"\"";
         }});
         target.value = items.join(",");
     });
    document.body.append(element);
}
